<template>
  <div class="user-management">
    <!-- 搜索和操作栏 -->
    <div class="search-bar">
      <el-form size="small" :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="手机号">
          <el-input v-model="searchForm.phone" placeholder="请输入手机号" clearable></el-input>
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="searchForm.nickname" placeholder="请输入昵称" clearable></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="1"></el-option>
            <el-option label="禁用" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" icon="el-icon-search">搜索</el-button>
          <el-button @click="resetSearch" icon="el-icon-refresh">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="operation-buttons">
        <el-button size="small" type="primary" @click="handleAdd" icon="el-icon-plus">新增用户</el-button>
      </div>
    </div>

    <!-- 用户列表 -->
    <div class="user-table">
      <el-table
          size="mini"
          v-loading="tableLoading"
          :data="userList"
          height="100%"
          style="width: 100%"
          row-key="id"
      >
        <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
        <el-table-column prop="nickname" label="昵称" min-width="120"></el-table-column>
        <el-table-column prop="phone" label="手机号" min-width="120"></el-table-column>
        <el-table-column prop="model_list" label="开通模型" min-width="150">
          <template slot-scope="scope">
            <el-tag
                v-for="(model, index) in scope.row.model_list"
                :key="index"
                size="mini"
                type="primary"
                effect="plain"
                class="model-tag"
            >
              {{ getModelName(model) }}
            </el-tag>
            <span v-if="!scope.row.model_list || scope.row.model_list.length === 0">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" min-width="150"></el-table-column>
        <el-table-column label="头像" width="80" align="center">
          <template slot-scope="scope">
            <el-avatar v-if="scope.row.avatar_url" :src="scope.row.avatar_url" :size="40"></el-avatar>
            <el-avatar v-else :size="40" icon="el-icon-user"></el-avatar>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template slot-scope="scope">
            <el-switch
                v-model="scope.row.status"
                :active-value="1"
                :inactive-value="0"
                active-color="#7E4CE0"
                inactive-color="#909399"
                @change="handleStatusChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间" min-width="160"></el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleEdit(scope.row)"
                class="action-button"
            >编辑</el-button>
            <el-button
                size="mini"
                type="text"
                icon="el-icon-key"
                @click="handleResetPassword(scope.row)"
                class="action-button"
            >重置密码</el-button>
            <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                class="action-button delete"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
      ></el-pagination>
    </div>

    <!-- 用户表单对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px" @close="resetForm">
      <el-form size="small" :model="userForm" :rules="userRules" ref="userForm" label-width="70px">
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="userForm.nickname" placeholder="请输入昵称"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogType === 'add'">
          <el-input v-model="userForm.password" placeholder="请输入密码" show-password></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="userForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="模型" prop="model_list">
          <el-select v-model="userForm.model_list" multiple placeholder="请选择模型" style="width: 100%">
            <el-option
              v-for="item in modelOptions"
              :key="item.id"
              :label="item.name"
              :value="item.model">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="userForm.remark" type="textarea" placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogVisible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog title="重置密码" :visible.sync="resetPwdVisible" width="400px">
      <el-form size="small" :model="resetPwdForm" :rules="resetPwdRules" ref="resetPwdForm" label-width="100px">
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="resetPwdForm.newPassword" placeholder="请输入新密码" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="resetPwdForm.confirmPassword" placeholder="请再次输入新密码" show-password></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="resetPwdVisible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="submitResetPwd" :loading="resetPwdLoading">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'
import {http} from "@/api";

export default {
  name: "UserManagement",
  data() {
    // 密码确认验证
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.resetPwdForm.newPassword) {
        callback(new Error('两次输入的密码不一致'));
      } else {
        callback();
      }
    };

    return {
      // 搜索表单
      searchForm: {
        phone: '',
        nickname: '',
        status: ''
      },
      // 表格数据
      userList: [],
      tableLoading: false,
      // 模型选项
      modelOptions: [],
      // 分页
      pagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      // 对话框
      dialogVisible: false,
      dialogTitle: '添加用户',
      dialogType: 'add', // add or edit
      submitLoading: false,
      // 用户表单
      userForm: {
        id: null,
        nickname: '',
        phone: '',
        email: '',
        password: '',
        status: 1,
        model_list: [],
        remark: ''
      },
      // 表单验证规则
      userRules: {
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        email: [
          { required: false, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
        ]
      },
      // 重置密码
      resetPwdVisible: false,
      resetPwdLoading: false,
      resetPwdForm: {
        id: null,
        newPassword: '',
        confirmPassword: ''
      },
      resetPwdRules: {
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入新密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    this.getUserList();
    this.getModelList();
  },
  methods: {
    // 获取模型列表
    getModelList() {
      http.model.list().then(res => {
        this.modelOptions = res.data || [];
      });
    },
    // 根据模型ID获取模型名称
    getModelName(modelId) {
      const model = this.modelOptions.find(item => item.model === modelId);
      return model ? model.name : modelId;
    },
    // 获取用户列表
    getUserList() {
      this.tableLoading = true;
      const params = {
        ...this.searchForm,
        pageNum: this.pagination.pageNum,
        pageSize: this.pagination.pageSize
      };

      http.user.page(params).then(res => {
        this.userList = res.data.rows;
        this.pagination.total = res.data.count;
        this.tableLoading = false;
      }).catch(() => {
        this.tableLoading = false;
      });
    },

    // 搜索
    handleSearch() {
      this.pagination.pageNum = 1;
      this.getUserList();
    },

    // 重置搜索
    resetSearch() {
      this.searchForm = {
        phone: '',
        nickname: '',
        status: ''
      };
      this.handleSearch();
    },

    // 分页大小变化
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.getUserList();
    },

    // 当前页变化
    handleCurrentChange(val) {
      this.pagination.pageNum = val;
      this.getUserList();
    },

    // 添加用户
    handleAdd() {
      this.dialogType = 'add';
      this.dialogTitle = '添加用户';
      this.dialogVisible = true;
    },

    // 编辑用户
    handleEdit(row) {
      this.dialogType = 'edit';
      this.dialogTitle = '编辑用户';
      this.userForm = {
        id: row.id,
        nickname: row.nickname,
        phone: row.phone,
        email: row.email,
        status: row.status,
        model_list: row.model_list || [],
        remark: row.remark
      };
      this.dialogVisible = true;
    },

    // 提交表单
    submitForm() {
      this.$refs.userForm.validate(valid => {
        if (valid) {
          this.submitLoading = true;

          if (this.userForm.id) {
            // 添加用户
            http.user.update(this.userForm.id,this.userForm).then(() => {
              this.$message.success('修改成功');
              this.dialogVisible = false;
              this.getUserList();
              this.submitLoading = false;
            }).catch(() => {
              this.submitLoading = false;
            });
          } else {
            // 编辑用户
            http.user.create(null, this.userForm).then(() => {
              this.$message.success('添加成功');
              this.dialogVisible = false;
              this.getUserList();
              this.submitLoading = false;
            }).catch(() => {
              this.submitLoading = false;
            });
          }
        }
      });
    },

    // 重置表单
    resetForm() {
      if (this.$refs.userForm) {
        this.$refs.userForm.resetFields();
      }
      this.userForm = {
        id: null,
        nickname: '',
        phone: '',
        email: '',
        password: '',
        status: 1,
        model_list: [],
        remark: ''
      };
    },

    // 状态变更
    handleStatusChange(row) {
      const statusText = row.status === 1 ? '启用' : '禁用';
      http.user.update(row.id, { status: row.status }).then(() => {
        this.$message.success(`${statusText}成功`);
      }).catch(() => {
        // 恢复原状态
        row.status = row.status === 1 ? 0 : 1;
        this.$message.error(`${statusText}失败`);
      });
    },

    // 重置密码
    handleResetPassword(row) {
      this.resetPwdForm.id = row.id;
      this.resetPwdVisible = true;
    },

    // 提交重置密码
    submitResetPwd() {
      this.$refs.resetPwdForm.validate(valid => {
        if (valid) {
          this.resetPwdLoading = true;

          // 直接更新用户密码
          http.user.update(this.resetPwdForm.id, {
            password: this.resetPwdForm.newPassword
          }).then(() => {
            this.$message.success('密码重置成功');
            this.resetPwdVisible = false;
            this.resetPwdLoading = false;
            // 重置表单
            if (this.$refs.resetPwdForm) {
              this.$refs.resetPwdForm.resetFields();
            }
            this.resetPwdForm = {
              id: null,
              newPassword: '',
              confirmPassword: ''
            };
          }).catch(() => {
            this.resetPwdLoading = false;
          });
        }
      });
    },

    // 删除用户
    handleDelete(row) {
      this.$confirm('确认删除该用户吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        http.user.delete(row.id).then(() => {
          this.$message.success('删除成功');
          this.getUserList();
        });
      }).catch(() => {});
    }
  }
};
</script>

<style scoped lang="scss">
.user-management {
  padding: 24px;
  flex-grow: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  .search-bar {
    background-color: #fff;
    padding: 24px;
    border-radius: 8px;
    margin-bottom: 24px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    display: flex;
    justify-content: space-between;
    align-items: flex-start;

    .search-form {
      flex: 1;
    }

    .operation-buttons {
      margin-left: 16px;

      .el-button--primary {
        background-color: #7E4CE0;
        border-color: #7E4CE0;

        &:hover, &:focus {
          background-color: #9670E5;
          border-color: #9670E5;
        }
      }
    }
  }
  .user-table {
    flex-grow: 1;
    overflow: hidden;
  }
  .el-table {
    border-radius: 8px;
    margin-bottom: 24px;
    overflow: auto;

    .action-button {
      color: #7E4CE0;

      &.delete {
        color: #F56C6C;
      }
    }
  }

  .pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 16px;
  }

  .el-button--primary {
    background-color: #7E4CE0;
    border-color: #7E4CE0;

    &:hover, &:focus {
      background-color: #9670E5;
      border-color: #9670E5;
    }
  }

  .el-switch__core {
    &:after {
      background-color: #fff;
    }
  }

  .model-tag {
    margin-right: 5px;
    margin-bottom: 5px;
    background-color: rgba(126, 76, 224, 0.1);
    border-color: rgba(126, 76, 224, 0.2);
    color: #7E4CE0;
  }
}
</style>
